<?php
/**
 * Created by PhpStorm.
 * User: Qch
 * Date: 2016/10/27
 * Time: 18:45
 */

namespace J\Util;


/**
 * 调试控制台
 */
class Console
{
    const MSG = 'text';
    const TIME = 'time';
    const USAGE = 'usage';
    const PEAK = 'peak';
    const LEVEL = 'type';
    const DEBUG = 'info';
    const ERROR = 'warning';

    protected $start = [
        self::MSG => '',
        self::TIME => START_TIME,
        self::USAGE => START_MEM,
        self::PEAK => START_MEM,
        self::LEVEL => self::DEBUG,
    ];

    /**
     * @var array 信息
     */
    protected $breakpoints = [];

    /**
     * 记录时间（微秒）和内存使用情况
     * @param string $message 标记位置
     * @param string $level
     * @return int
     */
    public function log($message, $level = self::DEBUG)
    {
        // 记录时间和内存使用
        $v = [];
        $v[self::MSG]   = $message;
        $v[self::TIME]  = microtime(true);
        $v[self::USAGE] = memory_get_usage();
        $v[self::PEAK]  = memory_get_peak_usage();
        $v[self::LEVEL] = $level;

//        if ($level === self::ERROR){
//            // $trace = debug_backtrace();
//            // die(debug_print_backtrace());
//        }

        // var_dump($message);

        $this->breakpoints[] = $v;

        return count($this->breakpoints) - 1;
    }

    /**
     * @return array
     */
    public function getTrace()
    {

        return $this->breakpoints;
    }

    /**
     * 统计从开始到统计时的时间（微秒）使用情况
     * @return integer
     */
    public static function getUseTime()
    {
        return number_format((microtime(true) - START_TIME));
    }

    /**
     * 统计从开始到统计时的内存使用情况
     * @return string
     */
    public static function getUseMem()
    {
        return format_memory_size(memory_get_usage() - START_MEM);
    }

    /**
     * 获取文件加载信息
     * @param bool  $detail 是否显示详细
     * @return integer|array
     */
    public static function getIncludedFiles($detail = false)
    {
        if ($detail) {
            $files = get_included_files();
            $info  = [];
            foreach ($files as $key => $file) {
                $info[] = $file . ' ( ' . number_format(filesize($file) / 1024, 2) . ' KB )';
            }
            return $info;
        }
        return count(get_included_files());
    }
}